//
//  DatePickerView.swift
//  Stock_Stategy
//
//  Created by MayerF on 2017/10/18.
//  Copyright © 2017年 MayerF. All rights reserved.
//

import UIKit

@objc protocol DatePickerViewDelegate {
    func datePickerClick(date: String)
}

class DatePickerView: UIView {
    let toolBar = UIToolbar()
    let picker = UIDatePicker()
    @objc var delegete: DatePickerViewDelegate?
    public var pickerFormat = "yyyy/MM/dd"
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initCommon()
        initConstraints()
    }
    
    private func initCommon() {
        picker.backgroundColor = .white
        toolBar.backgroundColor = UIColor(colorValue: 0xeaf0f5, alphaValue: 1.0)
        var tempArray = Array<UIBarButtonItem>()
        let cancelBtn = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(cancelBtnOnClick(_:)))
        let flexBtn = UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
        let doneBtn = UIBarButtonItem(title: "完成", style: .done, target: self, action: #selector(doneBtnOnClick))
        tempArray.append(cancelBtn)
        tempArray.append(flexBtn)
        tempArray.append(doneBtn)
        toolBar.setItems(tempArray, animated: true)
        
        picker.datePickerMode = .date
        let locale = Locale.init(identifier: "zh_CN")
        picker.locale = locale;
    }
    private func initConstraints() {
        addSubview(toolBar)
        addSubview(picker)
        
        toolBar.mas_makeConstraints { (make) in
            make?.top.left().right().mas_equalTo()(self)
            make?.height.mas_equalTo()(44)
        }
        picker.mas_makeConstraints { (make) in
            make?.top.mas_equalTo()(self.toolBar.mas_bottom)
            make?.left.right().bottom().mas_equalTo()(self)
        }
    }
    
    @objc func cancelBtnOnClick(_ btn: UIButton) {
        self.isHidden = true
    }
    @objc func doneBtnOnClick() {
        self.isHidden = true
        let date = picker.date
        let format = DateFormatter()
        format.dateFormat = pickerFormat
        delegete?.datePickerClick(date: format.string(from: date))
    }
    @objc public func setMode(mode: UIDatePicker.Mode) {
        picker.datePickerMode = mode
        if mode == .time {
            pickerFormat = "HH:mm:00"
        }else {
            pickerFormat = "yyyy/MM/dd"
        }
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
